package com.edu.dao.Impl;

import com.edu.dao.BaseDao;
import com.edu.dao.UserDao;
import com.edu.entity.Book;
import com.edu.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    public List<User> queryUser(String userName, String userPass) {
        Connection conn = BaseDao.getConn();//打开连接
        String sql = "SELECT * FROM user WHERE user_name='" + userName + "' AND user_pass='" + userPass + "'";
        System.out.println(sql);
        List<User> list = new ArrayList<User>();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setUser_id(rs.getInt("user_id"));
                user.setUser_name(rs.getString("user_name"));
                user.setUser_pass(rs.getString("user_pass"));
                user.setName(rs.getString("name"));
                list.add(user);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(conn, ps, rs);
        }
        return list;
    }


    @Override
    public int insertUser(User user) {
        String sql = "INSERT INTO user(user_name,user_pass,name) VALUES(?,?,?)";
        System.out.println(sql);
        Object[] param = {user.getUser_name(), user.getUser_pass(), user.getName()};
        int rowNum = BaseDao.executeUpdate(sql, param);
        return rowNum;
    }

    @Override
    public List<Book> queryBook() {
        Connection conn = BaseDao.getConn();
        String sql = "SELECT * FROM book";
        List<Book> list = new ArrayList<Book>();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Book book = new Book();
                book.setBook_id(rs.getInt("book_id"));
                book.setBook_name(rs.getString("book_name"));
                book.setBook_type(rs.getString("book_type"));
                book.setBookCreat_name(rs.getString("bookCreat_name"));
                list.add(book);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            BaseDao.closeAll(conn, ps, rs);
            return list;
        }
    }
}